<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Update extends CI_Controller {

    public function Update() {
        parent::__construct();

        $this->load->model('user_model', 'user');
        $this->load->model('host_model', "host");
        $this->load->model('zone_model', "zone");
    }

    public function index() {
        
    }

    public function ip() {
        echo $_SERVER['REMOTE_ADDR'];
    }

    public function host() {
        if (!isset($_SERVER['PHP_AUTH_USER'])) {
            header('WWW-Authenticate: Basic realm="Engelsoft"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'Autenticacao nessessaria!';
            exit;
        } else {
            $loginname = $_SERVER['PHP_AUTH_USER'];
            $loginpw = $_SERVER['PHP_AUTH_PW'];

            $user = $this->user->login($loginname);

            if ($user->password == md5($loginname . $loginpw)) {

                $hostsegment = $this->uri->segment(3);
                $ip = $this->uri->segment(4);

                if ((int) $hostsegment) {
                    $host = $this->host->id((int) $hostsegment);
                } else if (is_string($hostsegment)) {
                    $host = $this->host->host($hostsegment);
                }

                if ($host) {
                    $zone = $host->zone();

                    $ipsrv = $_SERVER['REMOTE_ADDR'];

//                verifica se o usuario é dono do host
                    if ($user->id == $host->user) {
//                    verifica variaveis necessárias
                        if ($ip && $ipsrv && $ip == $ipsrv && $host && $zone) {
                            if ($host->ip != $ip) {
                                echo "ok001 $host->host.$zone->name = $ip";
                                $this->host->update($host->id, false, false, $ip);
                            } else {
                                echo "ok002";
                            }
                        } else {
                            header('HTTP/1.0 401 Unauthorized');
                            echo "error99823";
                        }
                    } else {
                        header('HTTP/1.0 401 Unauthorized');
                        echo 'error99243';
                    }
                }
            } else {
                header('HTTP/1.0 401 Unauthorized');
                echo "Senha ou Usuario nao conferem";
            }
        }
    }

}
